//
//  WithdrawalsViewController.m
//  DaoZiJinFu
//
//  Created by woker on 16/6/27.
//  Copyright © 2016年 iwoker. All rights reserved.
//

#import "WithdrawalsViewController.h"
#import "AssetViewController.h"
#import "WithdrawalsSuccess.h"
#import "PaymentConfirm.h"
#import "ForgetPassword.h"
#import "checkModifyPwd.h"
#import "FAQforWithdrawals.h"

#define withdrawalDeadline 2

@interface WithdrawalsViewController () <checkModifyPwdDelegate,UITextFieldDelegate> {
    DZBankInfo *_bankInfo;
    checkModifyPwd *checkModify;
    BOOL isHavePoint;
}

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *nextBtnHeight;
@property (weak, nonatomic) IBOutlet UILabel *attention;


@end

@implementation WithdrawalsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupTitleView:@"提现"];
    self.view.backgroundColor = BACKGROUND_COLOR;
    [self leftButton:nil];
    [self rightButton];
    isHavePoint = NO;
    
    _bankInfo = [DZBankInfo mj_objectWithKeyValues:[DZUserInfo.userInfo.banks firstObject]];
    [_bankIcon sd_setImageWithURL:[NSURL URLWithString:_bankInfo.bank_logo_path] placeholderImage:[UIImage imageNamed:LOGO_PLACEHOLDER]];
    NSString *cardNum = _bankInfo.bank_card_number;
    _bankLab.text = [NSString stringWithFormat:@"%@ 尾号%@",_bankInfo.bank_name,[cardNum substringFromIndex:cardNum.length-4]];
    float money = [DZNsstringUtil floatInto:[DZUserInfo.userInfo.account_balance doubleValue]];
    _balanceLab.text = [NSString stringWithFormat:@"可提现金额：%.2lf",money];;
    _nextBtn.layer.masksToBounds = YES;
    _nextBtn.layer.cornerRadius = BTN_RADIUS;
    _nextBtnHeight.constant = 12;
    self.attention.hidden = YES;
    [self.withdrawalsMoney addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
}

- (void)textFieldDidChange:(UITextField *)text {
    if ([_withdrawalsMoney.text doubleValue] > [DZUserInfo.userInfo.withdraw_max_amount doubleValue]) {
       NSString *string = [NSString stringWithFormat:@"注意：因银行对单笔提现限制%@元，系统会将您的提现拆成多笔提现订单。",DZUserInfo.userInfo.withdraw_max_amount];
        self.attention.hidden = NO;
        self.attention.text = string;
        _nextBtnHeight.constant = 50;
    }else{
        _nextBtnHeight.constant = 12;
       self.attention.hidden = YES;
    }
}

- (void)rightBarItemOnClick:(id)sender {
    FAQforWithdrawals *faq = [[FAQforWithdrawals alloc] init];
    [self.navigationController pushViewController:faq animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

}

- (IBAction)nextClick:(id)sender {
    if ([DZUserInfo.userInfo.account_balance doubleValue] < [_withdrawalsMoney.text doubleValue]) {
        JSSHOW(@"提现金额大于可用余额");
        return;
    }
    if ([_withdrawalsMoney.text doubleValue] < withdrawalDeadline) {
        NSString *string = [NSString stringWithFormat:@"提现金额不低于%d元",withdrawalDeadline];
        JSSHOW(string);
        return;
    }
    checkModify = [checkModifyPwd showView:self.view withMoney:_withdrawalsMoney.text];
    checkModify.delegate = self;
}

- (void)doWithModifypwd:(NSString *)pwd {
    JSSHOWHUD;
    NSDictionary *params = @{@"bank_card_id":_bankInfo.id?:@"",
                             @"amount":_withdrawalsMoney.text,
                             @"pwd":pwd};
    DZRequestUtil *request = [[DZRequestUtil alloc] init];
    request.requestUrl = @"Order/createWithdrawOrder";
    request.params = params;
    [DZNetAPI request:request success:^(id response) {
        JSHIDEHUD;
        DZResponse *model = [DZResponse mj_objectWithKeyValues:response];
        if (model.rt == 1) {
            [checkModify removeFromSuperview];
            checkModify = nil;
            [CommTools setUserInfo:response];
            WithdrawalsSuccess *success = [[WithdrawalsSuccess alloc] init];
            success.withdrawalsMoney = _withdrawalsMoney.text;
            [self.navigationController pushViewController:success animated:YES];
        }else{
            JSSHOW(model.msg);
            [checkModify clearPwdText];
        }
    } failure:^(NSError *error) {
        JSSHOW(LOAD_FAIL_TIP);
    }];
}

- (void)resetModifyPwd {
    ForgetPassword *forget = [[ForgetPassword alloc] init];
    [self setupTitleView:@"忘记交易密码"];
    forget.telStr = DZUserInfo.userInfo.mobile;
    forget.sms_type = [NSString stringWithFormat:@"%d",3];
    [self.navigationController pushViewController:forget animated:YES];
    
}

- (IBAction)textChanged:(id)sender {
    if (_withdrawalsMoney.text.length) {
        _nextBtn.backgroundColor = BLUE_COLOR;
        _nextBtn.userInteractionEnabled = YES;
    } else {
        _nextBtn.backgroundColor = UNUSEABLECOLOR;
        _nextBtn.userInteractionEnabled = NO;
    }
}

- (void)leftBarItemOnClick:(id)sender {
    NSInteger index = NSIntegerMax;
    for (UIViewController *vc in self.navigationController.viewControllers) {
        if ([vc isMemberOfClass:[AssetViewController class]]) {
            index = [self.navigationController.viewControllers indexOfObject:vc];
            break;
        }
    }
    if (index != NSIntegerMax) {
        [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:index] animated:YES];
    } else {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}



- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
//    if (string.length && ![CommTools isPureNumandCharacters:string]) {
//        return NO;
//    }
    
    if (string.length == 0 && [textField.text isEqualToString:@"0."]) {
        textField.text = @"";
        isHavePoint = NO;
        return NO;
    }
    
    if ([textField.text rangeOfString:@"."].location == NSNotFound) {
        isHavePoint = NO;
    }
    
    if ([string length] > 0) {
        
        unichar single = [string characterAtIndex:0];//当前输入的字符
        if ((single >= '0' && single <= '9') || single == '.') {//数据格式正确
            //首字母不能为0和小数点
            if ([textField.text length] == 0) {
                if (single == '.') {
//                    [self showError:@"亲，第一个数字不能为小数点"];
                    textField.text = [textField.text stringByReplacingCharactersInRange:range withString:@"0."];
                    isHavePoint = YES;
                    return NO;
                }
                if (single == '0') {
//                    [self showError:@"亲，第一个数字不能为0"];
                    textField.text = [textField.text stringByReplacingCharactersInRange:range withString:@"0."];
                    isHavePoint = YES;
                    return NO;
                }
            }
            
            //输入的字符是否是小数点
            if (single == '.') {
                if(!isHavePoint) {//text中还没有小数点
                    isHavePoint = YES;
                    return YES;
                } else {
//                    [self showError:@"亲，您已经输入过小数点了"];
                    [textField.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                }
            } else {
                if (isHavePoint) {//存在小数点
                    //判断小数点的位数
                    NSRange ran = [textField.text rangeOfString:@"."];
                    NSLog(@"  %ld  %ld  %ld",range.location,ran.location,range.location-ran.location);
                    NSInteger dis = range.location - ran.location;
                    if (dis <= 2) {
                        return YES;
                    } else {
//                        [self showError:@"亲，您最多输入两位小数"];
                        return NO;
                    }
                } else {
                    return YES;
                }
            }
        } else {//输入的数据格式不正确
//            [self showError:@"亲，您输入的格式不正确"];
            [textField.text stringByReplacingCharactersInRange:range withString:@""];
            return NO;
        }
    } else {
        return YES;
    }
    return YES;
}

@end
